package com.sky.service.impl;

import com.sky.mapper.OrderMapper;
import com.sky.service.TurnoverReportService;
import com.sky.vo.TurnoverReportVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TurnoverReportServiceImpl implements TurnoverReportService {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 获取营业额
     * @param begin 开始时间
     * @param end   结束时间
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        // 存放从begin开始到end结束的日期
        List<LocalDate> dateList = new ArrayList<>();

        dateList.add(begin);
        while (!begin.equals(end)) {
            // 日期加1
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        // 存放每天的营业额
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            // 开始时间
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            // 结束时间
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            // 封装请求数据
            Map<String, Object> map = new HashMap<>();
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
            map.put("status", 5);

            // 查询营业额
            // 营业额（订单状态为已完成的金额合计）
            Double turnover = orderMapper.sumByOrderTimeBetween(map);
            // 特殊情况：当日营业额为null时，设置为0
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }

        // 封装返回的对象
        return TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }
}
